package com.yoomiito.app.ui.yijiayou

import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import com.yoomiito.app.R
import com.yoomiito.app.base.App
import com.yoomiito.app.base.BaseActivity
import com.yoomiito.app.base.WebViewActivity
import com.yoomiito.app.model.LatLng
import com.yoomiito.app.model.bean.BannerAndIconInfo
import com.yoomiito.app.model.oil.OilBannerData
import com.yoomiito.app.model.oil.OilStationData
import com.yoomiito.app.model.oil.OilStationDetailData
import com.yoomiito.app.showToast
import com.yoomiito.app.ui.anyview.gasstation.GasSortTabView
import com.yoomiito.app.utils.*
import com.yoomiito.app.widget.SpacingDecoration
import com.yoomiito.app.widget.dialog.SelectMapDialog
import com.yoomiito.app.widget.state.ContentType
import com.yoomiito.app.widget.state.EmptyType_2
import com.yoomiito.app.widget.state.ErrorType
import com.yoomiito.app.widget.state.StatusManager
import com.youth.banner.BannerConfig
import com.youth.banner.Transformer
import kotlinx.android.synthetic.main.act_gas_station_list_1.*
import kotlinx.android.synthetic.main.item_search_toolbar_1.*

class GasStationListActivity : BaseGasStationActivity<GasStationListPresenter>() {

    companion object {
        fun start(context: Context, latLng: LatLng) {
            val intent = Intent(context, GasStationListActivity::class.java)
            intent.putExtra(Const.Common.Data, latLng)
            context.startActivity(intent)
        }
    }

    private val mAdapter = GasStationListAdapter(null).also {
        it.setOnItemClickListener { adapter, view, position ->
            L.i("请求。。。。::: ${DebounceHelper.click(1)}")
//            DebounceHelper.click(1).compose(bindToLifecycle()).subscribe {_->
            L.i("开始请求。。。。")
            val data = it.data[position] as OilStationData
            showLoading()
            //调详情接口
            if (data.type == 1) {
                val gps = GPSConverterUtils.gcj02_To_Bd09(latLng.lat, latLng.lng)
                oilDetail(data.gasId, latLng, LatLng(gps.lat, gps.lon), data.type)
            } else {
                oilDetail(data.gasId, latLng, latLng, data.type)
            }
        }
//        }
        it.setOnItemChildClickListener { adapter, view, position ->
            val data = it.data[position] as OilStationData
            /*
            易加油 type=1 坐标为百度坐标
            团油 type=2 坐标为火星坐标系
            小桔 type=3 坐标为火星坐标系
             */
            if (data.type == 1) {
//                val converter = CoordinateConverter()
//                // CoordType.GPS 待转换坐标类型
//                converter.from(CoordinateConverter.CoordType.BAIDU)
//                // sourceLatLng待转换坐标点 LatLng类型
//                converter.coord(com.amap.api.maps2d.model.LatLng(data.lat.toDouble(), data.lng.toDouble()))
//                // 执行转换操作
//                val latlng: com.amap.api.maps2d.model.LatLng = converter.convert()
//                showSelectMap(latlng.latitude, latlng.longitude)
            } else {
                showSelectMap(data.lat.toDouble(), data.lng.toDouble())
            }

        }
    }

    private lateinit var mRefreshLayout: SmartRefreshLayout
    private lateinit var mRecyclerView: androidx.recyclerview.widget.RecyclerView

    private var mCurrentPage = 1
    private lateinit var latLng: LatLng
    private var sortType = GasSortTabView.DistanceSort //默认距离优先

    override fun getLayoutId(): Int = R.layout.act_gas_station_list_1

    override fun newP(): GasStationListPresenter = GasStationListPresenter(App.mAppConfig)

    override fun initData(savedInstanceState: Bundle?) {
        latLng = intent.getParcelableExtra(Const.Common.Data)
        back.setOnClickListener { finish() }
        itemSearchDel.visibility = View.GONE
        itemSearch.background = ColorUtils.background(R.color.color_F4F4F4, 16f)
        itemSearchEt.let {
            it.hint = "搜索附近的油站"
//            it.isCursorVisible = false
            it.isFocusable = false
            it.isFocusableInTouchMode = false
        }
        itemSearchEt.setOnClickListener {
            GasStationSearchActivity.start(this, latLng)
        }
        initAppbarLayout()
        initRcy()
        val shadeView = View(this)
        frameLayout.addView(shadeView, ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
        shadeView.setBackgroundResource(R.color.color_black_80)
        shadeView.visibility = View.GONE
        tabView.init(shadeView)
        tabView.onResultListener = {
            when (it) {
                -1 -> {//不处理
                }
                -2 -> {
                    sortType = GasSortTabView.DistanceSort
                    mAdapter.data.sortBy { sort -> sort.distance }
                    mAdapter.notifyDataSetChanged()

                }//距离优先
                -3 -> {
                    sortType = GasSortTabView.PriceSort
                    mAdapter.data.sortBy { sort -> sort.price }
                    mAdapter.notifyDataSetChanged()
                }//价格优先
                else -> {
                    oilNum = it
                    mCurrentPage = 1
                    showLoading()
                    requestList()
                }
            }
        }
        showLoading()
        banner()
        requestList()
    }

    private fun initAppbarLayout() {
        toolbarLl.setBackgroundResource(R.color.color_white)
//        appBarLayout.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { appBarLayout, i ->
//            when {
//                i == 0 -> {//展开
//                    toolbarLl.setBackgroundResource(R.color.color_tran)
//                    titleTv.visibility = View.INVISIBLE
//                    val d = show_new.background as GradientDrawable
//                    d.setColor(ResUtil.getColor(R.color.color_FF035B))
//                }
//                abs(i) >= appBarLayout.totalScrollRange -> {//折叠
//                    toolbarLl.background = ColorUtils.gradient("#FFFF246C", "#FFFF035B")
//                    titleTv.visibility = View.VISIBLE
//                    val d = show_new.background as GradientDrawable
//                    d.setColor(ResUtil.getColor(R.color.color_tran))
//                }
//                else -> {//中间
//                    toolbarLl.setBackgroundResource(R.color.color_tran)
//                    titleTv.visibility = View.INVISIBLE
////                    if (abs(i)>=appBarLayout.totalScrollRange/2){
////                        appBarLayout.setExpanded(false,true)
////                    }else{
////                        appBarLayout.setExpanded(true,true)
////                    }
//                }
//            }
//        })
    }

    private fun initRcy() {
        mStatusManager = StatusManager.Builder(this)
                .addType(ContentType(R.layout.fm_rcy))
                .addType(EmptyType_2().setEmptyContent("未找到油站\n请更改筛选条件"))
                .addType(ErrorType().setMarginTop(98).setClickListener {
                    showLoading()
                    mCurrentPage = 1
                    requestList()
                })
                .build()
        mRefreshLayout = mStatusManager.view().findViewById(R.id.fm_refreshLayout)
        mRefreshLayout.setOnLoadMoreListener {
            mCurrentPage++
            requestList()
        }
        mRefreshLayout.setEnableRefresh(false)
        mRecyclerView = mStatusManager.view().findViewById(R.id.fm_rcy)
        frameLayout.addView(mStatusManager.view(), FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
        mRecyclerView.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(this)
        mRecyclerView.addItemDecoration(SpacingDecoration(0, DensityUtil.dp2px(5f), false))
        mRecyclerView.adapter = mAdapter
        showOrderTv.background = ColorUtils.gradientAndRadius("#80000000", "#80000000", 0f, 12f, 0f, 12f)
    }

    private fun initBanner(bannerData: List<BannerAndIconInfo>) {
        val data = mutableListOf<String>()
        if (bannerData != null && bannerData.isNotEmpty()) {
            bannerData.forEach {
                data.add(it.image_url)
//                data.add("https://mimitao-cdn.aijiamai.com/FpBnbNVepoaMyfebOishmpXlomdB")
            }
        }
        //设置banner样式
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR)
        //设置图片加载器
        banner.setImageLoader(BannerImageLoader())
        //设置图片集合
        banner.setImages(data)
        //设置banner动画效果
        banner.setBannerAnimation(Transformer.Default)
        //设置标题集合（当banner样式有显示title时）
//        banner.setBannerTitles(titles);
        //设置自动轮播，默认为true
        banner.isAutoPlay(true)
        //设置轮播时间
        banner.setDelayTime(2500)
        //设置指示器位置（当banner模式中有指示器时）
        banner.setIndicatorGravity(BannerConfig.CENTER)
        //banner设置方法全部调用完毕时最后调用
        banner.setOnBannerListener {
            ActTypeUtils.handleActFromType(this, bannerData[it])
        }
        banner.start()
    }

    private fun banner() {
        p.banner()
    }

    private fun requestList() {
        p.list(oilNum, latLng, mCurrentPage)
    }

    fun setData(data: MutableList<OilStationData>?) {
        dismissLoading()
        if (data.isNullOrEmpty()) {
            if (mCurrentPage == 1) {
                mAdapter.setNewData(arrayListOf<OilStationData>())
                mStatusManager.showEmpty(EmptyType_2::class.java)
            } else {
                mRefreshLayout.finishLoadMoreWithNoMoreData()
            }
        } else {
            when(sortType){
                GasSortTabView.DistanceSort->{
                    data?.sortBy { sort -> sort.distance }
                }
                GasSortTabView.PriceSort->{
                    data?.sortBy { sort -> sort.price }
                }
            }
            if (mCurrentPage == 1) {
                mAdapter.setNewData(data)
                mStatusManager.showContent()
                mRefreshLayout.setNoMoreData(false)
            } else {
                mAdapter.addData(data)
            }
            mRefreshLayout.finishLoadMore()
        }
    }

    fun setBanner(data: OilBannerData?) {
        data?.let {
            initBanner(it.banner)
            showOrderTv.setData(it.discount)
        }
    }

    override fun showErrorView() {
        mRefreshLayout.finishLoadMore()
        if (mCurrentPage == 1) {
            super.showErrorView()
        } else {
            "数据请求超时，请稍后再试".showToast()
        }
    }

    override fun onStop() {
        super.onStop()
        dismissLoading()
    }
}